package com.cypher.encryptionanddecryption.fragment.maintain;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.cypher.encryptionanddecryption.R;
import com.cypher.encryptionanddecryption.activity.BluetoothCommunicationActivity;
import com.cypher.encryptionanddecryption.adapter.BluetoothTalkAdapter;
import com.cypher.encryptionanddecryption.bean.CommunicationBean;
import com.cypher.encryptionanddecryption.bean.OtaBean;
import com.cypher.encryptionanddecryption.bluetooth.BluetoothGattManager;
import com.cypher.encryptionanddecryption.bluetooth.BluetoothManagerSingleton;
import com.cypher.encryptionanddecryption.util.HexUtils;
import com.cypher.encryptionanddecryption.util.Nb25ProtocolUtils;
import com.cypher.encryptionanddecryption.util.ProgressDialogUtil;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 阀门状态读写界面
 * @author: 古霸天
 * @date: 2020/11/16
 */
public class OtaProgramDownloadFragment extends Fragment {
    private OtaBean bean;
    private Spinner content;
    private ListView resultEdit;
    private Button downloadBtn;
    private String[] mtuValues = {"256", "128"};
    private BluetoothGattManager gattManager;
    private Activity mActivity;
    private BluetoothTalkAdapter talkAdapter;
    private Handler handler;
//    private ProgressDialog dialog;
    public OtaProgramDownloadFragment(OtaBean bean) {
        this.bean = bean;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mActivity = (Activity) context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_ota_program_download, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        init(view);
        initListener();
    }

    /**
     * 初始化页面
     */
    private void init(View v) {
        handler = new Handler();
        content = v.findViewById(R.id.spinner_mtu);
        downloadBtn = v.findViewById(R.id.program_download_btn);

        resultEdit = v.findViewById(R.id.program_download_result);
        // 创建列表适配器
        talkAdapter =  new BluetoothTalkAdapter(v.getContext());
        // 初始化适配器数据集合
        talkAdapter.setContents(new ArrayList<>());
        talkAdapter.notifyDataSetChanged();
        resultEdit.setAdapter(talkAdapter);

        ArrayAdapter adapter = new ArrayAdapter<>(v.getContext(), R.layout.spinner_item, mtuValues);
        adapter.setDropDownViewResource(R.layout.dropdown_stytle);
        content.setAdapter(adapter);

        // 获取蓝牙连接管理类
        gattManager = BluetoothManagerSingleton.getInstance().getBluetoothGattManager();

//        dialog = new ProgressDialog(mActivity, R.style.AlertDialog);
    }

    private void initListener() {
        downloadBtn.setOnClickListener((v) -> {
            String bockSize = "0" + (content.getSelectedItemPosition() + 1);
            // 每次执行下载清空之前列表数据
            clearList();
//            dialog.setMessage("正在升级...");
//            dialog.show();
            downloadBtn.setEnabled(false);
            downloadBtn.setText("下载中");
            downloadBtn.setBackground(ContextCompat.getDrawable(downloadBtn.getContext(), R.drawable.shape_corner_cyan));
            insertEdit("正在升级中，请您耐心等待...");
            ProgressDialogUtil.showProgressDialog(mActivity, "正在升级...");
            // 蓝牙读取耗时间长，需要在子线程中处理
            // 该线程执行发送数据操作
            new Thread(() -> {
                handler.post(() -> {
                    clearList();
                    send(bockSize, Integer.parseInt(String.valueOf(content.getSelectedItem())));
//                    dialog.dismiss();
                    ProgressDialogUtil.dismiss(mActivity);
                    downloadBtn.setEnabled(true);
                    downloadBtn.setText("下载");
                    downloadBtn.setBackground(ContextCompat.getDrawable(downloadBtn.getContext(), R.drawable.button_select_blue));
                });
            }).start();
        });
    }


    private void send(String bockSizeHex, int mtu) {
        // 尾部数据
        String endHexCode = "";
        int endHexCodeLength = 0;
        // 下载程序代码
        String hexCode = bean.getData();
        int hexCodeLength = hexCode.length();
        // 计算下载次数
        int count = hexCodeLength / mtu;
        // 取尾部数据
        if ((hexCodeLength % mtu) != 0) {
            endHexCodeLength = hexCodeLength - (count * mtu);
            endHexCode = hexCode.substring(hexCodeLength - endHexCodeLength);
        }

        // 发送数据
        for (int i = 0; i < count; i++) {
            String messageID = HexUtils.intToHex(i + 1, 2);
            String data = hexCode.substring(mtu * i, (i + 1) * mtu);
            if (!sendData(getData(bockSizeHex, mtu, count, messageID, data), i + 1)) {
                return;
            }
        }

        // 发送尾部数据
        if (endHexCodeLength > 0) {
            String messageID = HexUtils.intToHex(count + 1, 2);
            if (sendData(getData(bockSizeHex, mtu, count, messageID, endHexCode),
                    count + 1)) {
                insertEdit("升级成功！升级成功！升级成功！");
            }
        }
    }

    /**
     * 获取需要下载的数据
     * @param bockSizeHex 获取数据
     * @param mtu mtu类型代码
     * @param count 每次下载大小
     * @param messageID 消息序号
     * @param hexCode 下载数据代码
     * @return
     */
    private String getData(String bockSizeHex, int mtu, int count, String messageID, String hexCode) {
        StringBuffer data = new StringBuffer();

        data.append("01").append(bockSizeHex).append(HexUtils.intToHex(count + 1, 2))
                .append(messageID)
                .append(HexUtils.intToHex(mtu, 4))
                .append(hexCode);

        return Nb25ProtocolUtils.getCommand(messageID, "9001", data.toString(), "95", 1);
    }

    /**
     * 向硬件发送数据
     * @param data 需要发送的数据
     * @param index 第几帧
     */
    private boolean sendData(String data, int index) {

        // 每次在发起命令的时候都需要设置接收状态为false
        // 以防其他设备向下位机发送信息，
        // 下位机回传命令到蓝牙
        gattManager.setReceiveData(false);

        // 发送命令到设备
        gattManager.sendMsg(HexUtils.hexToBytes(data));
        // 发送码加入对话列表中
        gattManager.addList("<- " + HexUtils.formatHex(data));

        // 校验程序是否下载成功
        if (gattManager.checkData("", mActivity)) {
            String receiveData = HexUtils.bytesToHex(gattManager.getBuf());
            int receiveDataLength = receiveData.length();
            if (StringUtils.equals("00", receiveData.substring(receiveDataLength - 8, receiveDataLength -6))) {
                insertEdit("第" + index + "帧发送成功：" + HexUtils.bytesToHex(gattManager.getBuf()));
                return true;
            }
        }
        insertEdit("升级失败！");
        return false;
    }

    /**
     * 文本框追加数据
     * @param content
     */
    private void insertEdit(String content) {
        talkAdapter.getContents().add(content);
        talkAdapter.notifyDataSetChanged();
    }

    private void clearList() {
        talkAdapter.getContents().clear();
        talkAdapter.notifyDataSetChanged();
    }
}
